import { defineStore } from 'pinia'
import { ref } from 'vue'
//引入接口
import { reqUserLoginByPwd, reqUserLoginByEmail } from '@/api/auth'
import type { EmailAndCaptchaParams, UserLoginParams } from '@/api/auth/type'
import { reqGetUserInfo } from '@/api/user'
//引入操作本地存储的工具方法
import { SET_TOKEN, GET_TOKEN, REMOVE_TOKEN } from '@/utils/token'
import { ElMessage, ElNotification } from 'element-plus'
import pinia from '..'
import { UserInfoRes } from '@/api/user/type'
import router from '@/router'
import { getTodayTask } from '@/api/task'
import { AllTaskList } from '@/api/task/type'

const api = import.meta.env.VITE_APP_BASE_API as string

//创建用户小仓库
const useUserStore = defineStore('User', () => {
  const token = ref<string>(GET_TOKEN() as string)
  const userInfo = ref<UserInfoRes>({
    id: 0,
    account: '',
    nickname: '',
    introduction: '',
    email: '',
    avatar: '',
    colorTheme: '',
    createdTime: '',
    ringtone: {
      id: 0,
      ringtoneName: '',
      ringtoneFile: '',
      ringtoneDuration: 0,
      createdDate: '',
    },
  })
  const todayTasks = ref<AllTaskList[]>()
  async function userLogin(params: UserLoginParams) {
    try {
      const { data } = await reqUserLoginByPwd(params)
      //pinia仓库存储一下token
      //由于pinia|vuex存储数据其实利用js对象
      token.value = data.token
      //本地存储持久化存储一份
      SET_TOKEN(token.value)
      await getUserInfo()
      await router.replace({ name: 'home' })
    } catch (error) {
      //登录失败的提示信息
      ElMessage({
        type: 'error',
        message: (error as Error).message,
      })
    }
  }

  async function userLoginByEmail(params: EmailAndCaptchaParams) {
    try {
      const { data } = await reqUserLoginByEmail(params)
      //pinia仓库存储一下token
      //由于pinia|vuex存储数据其实利用js对象
      token.value = data.token
      //本地存储持久化存储一份
      SET_TOKEN(token.value)
      await getUserInfo()
      await router.replace({ name: 'home' })
    } catch (error) {
      //登录失败的提示信息
      ElMessage({
        type: 'error',
        message: (error as Error).message,
      })
    }
  }

  async function getUserInfo() {
    try {
      const { data } = await reqGetUserInfo()
      userInfo.value = data
      initColorTheme()
      getUserTodayTask()
    } catch (error) {
      ElMessage({
        type: 'error',
        message: (error as Error).message,
      })
    }
  }

  async function getUserTodayTask() {
    const { data } = await getTodayTask()
    todayTasks.value = data
    console.log('jijjinjin',todayTasks.value)
    // todayTasks.value = [
    //   {
    //     id: 1,
    //     taskTitle: '看病',
    //     content: '去某医院看病',
    //     time: '2024-03-22 20:56:00',
    //     reminderLevel: 1,
    //     dayOfWeek: '星期一',
    //     weeklyPlanId: 0,
    //     completionStatus: 1,
    //   },
    //   {
    //     id: 2,
    //     taskTitle: '看电影',
    //     content: '去某医院看病',
    //     time: '2024-03-23 13:39:00',
    //     reminderLevel: 1,
    //     dayOfWeek: '星期一',
    //     weeklyPlanId: 0,
    //     completionStatus: 1,
    //   },
    // ]
    setNotification()
  }

  function setNotification() {
    todayTasks.value.forEach(async (task: any) => {
      if (task.completionStatus === 0) {
        let notificationTime = new Date(task.time).getTime()
        // 加上8小时
        // notificationTime.setHours(notificationTime.getHours() + 8);
        const currentTime = new Date().getTime()
        // currentTime.setHours(currentTime.getHours() + 8);
        // 简单输出格式化后的时间
        console.log('事务提醒时间',new Date(notificationTime))
        console.log('当前时间',new Date(currentTime))
        const delay = notificationTime - currentTime
        console.log('延迟:',delay)
        if (delay >= 0) {
          setTimeout(() => {
            console.log('tiping~')
            ElNotification({
              title: task.taskTitle,
              dangerouslyUseHTMLString: true,
              message:
                `<span>` +
                task.content +
                `<span><audio preload autoplay loop src="` +
                api +
                userInfo.value.ringtone.ringtoneFile +
                `"></audio>`,
              duration: 0,
              type:
                task.reminderLevel === 0
                  ? 'error'
                  : task.reminderLevel === 1
                  ? 'warning'
                  : 'info',
            })
          }, delay)
        } else {
          ElNotification({
            title: task.taskTitle + '（已超时）',
            dangerouslyUseHTMLString: true,
            message: `<span>` + task.content + `<span>`,
            duration: 0,
            type: 'warning',
          })
          // 此处修改事务状态为逾期状态，之后不提示(completionStatus = 2)
        }
      }
    })
  }

  async function userLogout() {
    REMOVE_TOKEN()
    token.value = ''
    await router.replace({ name: 'login' })
  }

  function initColorTheme() {
    //通知js修改根节点的样式对象的属性与属性值
    const html = document.documentElement
    html.style.setProperty('--el-color-primary', userInfo.value.colorTheme)
    html.style.setProperty(
      '--el-color-primary-light-3',
      userInfo.value.colorTheme,
    )
    html.style.setProperty(
      '--el-color-primary-dark-2',
      userInfo.value.colorTheme,
    )
  }

  return {
    token,
    userInfo,
    todayTasks,
    userLogout,
    userLogin,
    userLoginByEmail,
    getUserInfo,
  }
})
//对外暴露获取小仓库方法
export default useUserStore

// 非setup
export function useUserStoreHook() {
  return useUserStore(pinia)
}
